<template>
  <!-- 费用申请 -->
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="120px"
    >
      <el-form-item label="客户名称" prop="customerId">
        <el-select
          v-model="queryParams.customerId"
          placeholder="请选择客户名称"
          filterable
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="customer in customerList"
            :key="customer.customerId"
            :label="customer.customerName"
            :value="customer.customerId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商机名称" prop="orderId">
        <el-select
          v-model="queryParams.orderId"
          placeholder="请选择商机名称"
          filterable
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="order in orderListAll"
            :key="order.orderId"
            :label="order.orderName"
            :value="order.orderId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所属人" prop="userId">
        <el-select
          v-model="queryParams.userId"
          placeholder="请选择所属人"
          style="width: 100%"
          filterable
          clearable
        >
          <el-option
            v-for="user in userList"
            :key="user.userId"
            :label="user.userName"
            :value="user.userId"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['crm:apply:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['crm:apply:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['crm:apply:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['crm:apply:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="applyList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="费用名称"
        width="120"
        align="center"
        prop="applyName"
      />
      <el-table-column
        label="客户名称"
        width="120"
        align="center"
        prop="customerName"
      />
      <el-table-column
        label="商机名称"
        width="180"
        align="center"
        prop="orderName"
      />
      <el-table-column
        label="申请日期"
        align="center"
        prop="applyTime"
        width="100"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.applyTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合计金额" align="center" prop="amount" />
      <el-table-column label="是否核销" align="center" prop="isAdjust">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.is_adjust"
            :value="scope.row.isAdjust"
          />
        </template>
      </el-table-column>
      <!-- <el-table-column label="原借款" align="center" prop="loan" />
      <el-table-column label="应退款" align="center" prop="refund" /> -->
      <el-table-column label="申请人" align="center" prop="createBy" />
      <el-table-column
        label="费用归属"
        align="center"
        prop="applyAscription"
        width="90"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_data_ascription"
            :value="scope.row.applyAscription"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="所属小组"
        width="90"
        align="center"
        prop="groupId"
      >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.crm_group" :value="scope.row.groupId" />
        </template>
      </el-table-column>
      <el-table-column label="所属部门" align="center" prop="deptName" />
      <el-table-column label="所属人" align="center" prop="userName" />
      <el-table-column
        label="审核状态"
        width="90"
        align="center"
        prop="auditStatus"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_audit_status"
            :value="scope.row.auditStatus"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="200"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="submit(scope.row)"
            v-show="scope.row.auditStatus === '0'"
            >提交</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-refresh-left"
            @click="cancelInfo(scope.row)"
            v-show="scope.row.auditStatus === '1'"
            >撤回</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['crm:apply:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['crm:apply:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改费用申请对话框 -->
    <el-drawer
      ref="drawer"
      :title="title"
      direction="rtl"
      :visible.sync="open"
      size="60%"
      append-to-body
      :wrapperClosable="false"
    >
      <el-card
        class="box-card"
        style="width: 96%; margin-left: 20px; min-height: 90vh"
      >
      <div slot="header" class="clearfix">
        <span>费用申请</span>
        <el-button style="float: right; padding: 5px" type="primary"  v-print="'#formTable'" @click="handlePrint">打印</el-button>
      </div>
        <el-row>
          <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-col :span="12">
              <el-form-item label="费用名称" prop="applyName">
                <el-input
                  v-model="form.applyName"
                  placeholder="请输入费用名称"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请日期" prop="applyTime">
                <el-date-picker
                  style="width: 100%"
                  clearable
                  v-model="form.applyTime"
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="请选择申请日期"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="费用归属" prop="applyAscription">
                <el-select
                  v-model="form.applyAscription"
                  filterable
                  placeholder="请选择费用归属"
                  style="width: 100%"
                >
                  <el-option
                    v-for="dict in dict.type.sys_data_ascription"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12" v-if="form.applyAscription === '2'">
              <el-form-item label="所属小组" prop="groupId">
                <el-select
                  v-model="form.groupId"
                  filterable
                  placeholder="请选择所属小组"
                  style="width: 100%"
                >
                  <el-option
                    v-for="dict in dict.type.crm_group"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="form.applyAscription === '1'">
              <el-form-item label="所属部门" prop="deptId">
                <treeselect
                  v-model="form.deptId"
                  :options="deptOptions"
                  :show-count="true"
                  placeholder="请选择所属部门"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="form.applyAscription === '0'">
              <el-form-item label="所属人" prop="userId">
                <el-select
                  v-model="form.userId"
                  placeholder="请选择所属人"
                  style="width: 100%"
                  filterable
                  clearable
                >
                  <el-option
                    v-for="user in userList"
                    :key="user.userId"
                    :label="user.userName"
                    :value="user.userId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="客户名称" prop="customerId">
                <el-select
                  v-model="form.customerId"
                  filterable
                  placeholder="请选择客户名称"
                  style="width: 100%"
                  @change="getCrmOrderAllNoPage(form.customerId)"
                >
                  <el-option
                    v-for="customer in customerList"
                    :key="customer.customerId"
                    :label="customer.customerName"
                    :value="customer.customerId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商机名称" prop="orderId">
                <el-select
                  v-model="form.orderId"
                  filterable
                  placeholder="请选择商机名称"
                  style="width: 100%"
                >
                  <el-option
                    v-for="order in orderList"
                    :key="order.orderId"
                    :label="order.orderName"
                    :value="order.orderId"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label="费用明细" prop="details" class="details">
                <el-table :data="form.detailList" style="width: 100%">
                  <el-table-column label="报销项目" prop="project" width="280">
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.detailsName"
                        placeholder="请输入报销项目"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="摘要"
                    prop="detailsSummary"
                    width="280"
                  >
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.detailsSummary"
                        placeholder="请输入摘要"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="金额"
                    prop="detailsAmount"
                    width="280"
                  >
                    <template slot-scope="scope">
                      <el-input
                        v-model="scope.row.detailsAmount"
                        type="number"
                        placeholder="请输入金额"
                      />
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="操作"
                    align="center"
                    class-name="small-padding fixed-width"
                  >
                    <template slot-scope="scope">
                      <el-button
                        v-if="scope.$index === form.detailList.length - 1"
                        size="mini"
                        type="text"
                        icon="el-icon-plus"
                        @click="addExpenses"
                        >新增</el-button
                      >
                      <el-button
                        v-else
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="delExpenses(scope.$index)"
                        >删除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="合计金额" prop="amount">
                <el-input
                  v-model.number="form.amount"
                  placeholder="请输入合计金额"
                  type="number"
                  readonly
                >
                  <template slot="append">{{
                    digitUppercase(form.amount)
                  }}</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="form.remark"
                  type="textarea"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item>
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
      </el-card>
    </el-drawer>

    <applyPrint
      id="formTable"
      :tabledata="form"
      :ownerList="userList"
      :customerList="customerList"
      :orderList="orderListAll"
      v-show="showProjectApproval"
    />
  </div>
</template>

<script>
import {
  listApply,
  getApply,
  delApply,
  addApply,
  updateApply,
  submit,
  cancelInfo,
} from "@/api/crm/apply";
import { deptTreeSelect } from "@/api/system/user";
import { getCrmOrderAllNoPage } from "@/api/crm/order";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getCrmCustomerAllNoPage } from "@/api/crm/customer";
import { getUserListByStatus } from "@/api/system/user";


import applyPrint from "../pc/components/applyPrint.vue";
export default {
  name: "Apply",
  components: { Treeselect, applyPrint },
  dicts: ["sys_audit_status", "sys_data_ascription", "is_adjust", "crm_group"],
  data() {
    return {
      // 遮罩层
      loading: true,
      showProjectApproval: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 费用申请表格数据
      applyList: [],
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 部门名称
      deptName: undefined,
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerId: null,
        orderId: null,
        applyTime: null,
        amount: null,
        loan: null,
        refund: null,
        userId: null,
        instanceId: null,
        nodeCode: null,
        nodeName: null,
        flowStatus: null,
      },
      customerList: [],
      orderList: [],
      orderListAll: [],
      userList: [],
      // 表单参数
      form: {
        applyAscription: "0",
        detailList: [
          { detailsName: "", detailsSummary: "", detailsAmount: null },
        ],
      },
      // 表单校验
      rules: {
        applyTime: [
          { required: true, message: "申请时间不能为空", trigger: "change" },
        ],
        amount: [
          { required: true, message: "费用金额不能为空", trigger: "bulr" },
        ],
        applyAscription: [
          { required: true, message: "费用归属不能为空", trigger: "change" },
        ],
        details: {
          required: true,
          validator: this.validateDetails,
          trigger: "blur",
        },
      },
    };
  },
  watch: {
    "form.detailList": {
      handler() {
        this.form.amount = this.form.detailList.reduce((total, item) => {
          return total + (Number(item.detailsAmount) || 0);
        }, 0);
      },
      deep: true,
    },
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    },
  },
  created() {
    this.getDeptTree();
    this.getList();
    this.getCrmCustomerAllNoPage();
    this.getUserListByStatus();
    getCrmOrderAllNoPage({}).then((res) => {
      this.orderListAll = res.data;
    });
  },
  methods: {
    handlePrint() {
      this.showProjectApproval = true;
      setTimeout(() => {
        this.showProjectApproval = false;
      }, 2000);
    },
    getUserListByStatus() {
      getUserListByStatus({ status: "0" }).then((res) => {
        this.userList = res.data;
      });
    },

    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    submit(row) {
      submit(row).then((res) => {
        this.$message.success("提交成功");
        this.getList();
      });
    },
    cancelInfo(row) {
      cancelInfo(row).then((res) => {
        this.$message.success("撤回成功");
        this.getList();
      });
    },
    validateDetails(rule, value, callback) {
      const isValid = this.form.detailList.every((item) => {
        return item.detailsName && item.detailsSummary && item.detailsAmount; // 检查每一项必填
      });
      if (!isValid) {
        callback(new Error("费用明细的每一项都必须填写完整"));
      } else {
        callback();
      }
    },
    addExpenses() {
      this.form.detailList.push({
        detailsName: "",
        detailsSummary: "",
        detailsAmount: "",
      });
    },
    delExpenses(index) {
      this.form.detailList.splice(index, 1);
    },
    getCrmOrderAllNoPage(customerId) {
      getCrmOrderAllNoPage({ customerId: customerId }).then((res) => {
        this.orderList = res.data;
        this.form.orderId = "";
      });
    },
    getCrmCustomerAllNoPage() {
      getCrmCustomerAllNoPage({}).then((res) => {
        this.customerList = res.data;
      });
    },
    /** 查询费用申请列表 */
    getList() {
      this.loading = true;
      listApply(this.queryParams).then((response) => {
        this.applyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        applyId: null,
        customerId: null,
        orderId: null,
        applyTime: null,
        amount: null,
        loan: null,
        refund: null,
        remark: null,
        userId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
        instanceId: null,
        nodeCode: null,
        nodeName: null,
        flowStatus: null,
        applyAscription: "0",
        detailList: [
          { detailsName: "", detailsSummary: "", detailsAmount: null },
        ],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.applyId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加费用申请";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const applyId = row.applyId || this.ids;
      getApply(applyId).then((response) => {
        this.form = response.data;
        getCrmOrderAllNoPage({ customerId: this.form.customerId }).then(
          (res) => {
            this.orderList = res.data;
          }
        );
        this.open = true;
        this.title = "修改费用申请";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.applyId != null) {
            updateApply(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addApply(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const applyIds = row.applyId || this.ids;
      this.$modal
        .confirm('是否确认删除费用申请编号为"' + applyIds + '"的数据项？')
        .then(function () {
          return delApply(applyIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "crm/apply/export",
        {
          ...this.queryParams,
        },
        `apply_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style scoped>
::v-deep .details .el-table--medium .el-table__cell {
  padding: 0;
}

::v-deep .details .el-input--medium {
  margin: 10px 10px 10px -10px;
}
</style>